import logging
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.utils import timezone
from datetime import datetime, timedelta
import json
from dateutil.parser import parse
import calendar
from django.views import View
from django.contrib import messages

from core.models import (
    SchoolSchedule, Semester, Grade, ClassInfo, GradeSchedule, 
    ClassCourse, CoursePeriod, ClassSubjectAssignment, TeacherSubjectAssignment
)
from core.views.utils import get_user_role
from core.forms.class_course_form import ClassCourseForm
from core.forms.grade_schedule_form import GradeScheduleForm
from core.models import Subject
from .utils import get_user_subject_classes
# 配置日志
logger = logging.getLogger(__name__)


def _get_current_semester():
    """获取当前学期"""
    return Semester.objects.filter(is_current=True).first()


def _get_class_subjects(class_id):
    """获取班级的所有学科"""
    if not class_id:
        return []
    subject_ids = ClassSubjectAssignment.objects.filter(
        class_id=class_id
    ).values_list('subject_id', flat=True)
    return Subject.objects.filter(id__in=subject_ids)


def _prepare_common_context(grade_id=None, class_id=None):
    """准备通用上下文数据"""
    current_semester = _get_current_semester()
    grade = None
    if grade_id:
        try:
            grade = Grade.objects.get(id=grade_id)
        except Grade.DoesNotExist:
            pass

    # 创建表单
    class_course_form = ClassCourseForm()
    grade_schedule_form = GradeScheduleForm()

    # 过滤班级学科选项
    if class_id:
        subject_ids = ClassSubjectAssignment.objects.filter(
            class_id=class_id
        ).values_list('subject_id', flat=True)
        class_course_form.fields['class_subject'].queryset = Subject.objects.filter(
            id__in=subject_ids
        )

    class_subjects = _get_class_subjects(class_id)
    grades = Grade.objects.all()
    return {
        'grades': grades,
        'grade': grade,
        'grade_id': grade_id,
        'class_id': class_id,
        'current_semester': current_semester,
        'class_course_form': class_course_form,
        'grade_schedule_form': grade_schedule_form,
        'class_subjects': class_subjects
    }


class ScheduleManager:
    """独立的日程管理功能类"""

    @staticmethod
    @login_required
    def index(request):
        """日程管理主页面"""
        try:
            user = request.user
            # 获取用户当前的角色
            current_role = request.session.get('CURRENT_ROLE')
            if current_role is None:
                current_role = get_user_role(request.user)
                request.session['CURRENT_ROLE'] = current_role
            current_semester = _get_current_semester()

            # 获取用户所在的班级，可能有多个班级
            # classes = ClassInfo.objects.filter(
            #     id__in=ClassSubjectAssignment.objects.filter(
            #         subject_id__in=TeacherSubjectAssignment.objects.filter(
            #             teacher=request.user
            #         ).values_list('subject_id', flat=True)
            #     ).values_list('class_id', flat=True)
            # ).distinct()
           
            classes=get_user_subject_classes(request.user)
            # 获取用户所在的年级，可能有多个年级
            grade_id_list = classes.values_list('grade_id', flat=True).distinct()
            grades = Grade.objects.filter(id__in=grade_id_list)
            managed_grade = grades.filter(grade_leader=request.user).first()
            managed_class = classes.filter(homeroom_teacher=request.user).first()

            context = {
                'current_role': current_role,
                'current_semester': current_semester,
                'grades': grades,
                'classes': classes,
                'managed_grade': managed_grade,
                'managed_class': managed_class,
            }
            return render(request, 'schedule_manager/index.html', context)
        except Exception as e:
            logger.error(f"日程管理主页面加载失败: {str(e)}", exc_info=True)
            messages.error(request, f"页面加载失败: {str(e)}")
            return render(request, 'schedule_manager/index.html', {})



    @staticmethod
    @login_required
    def schedule_manager_grade_list(request, grade_id=None):
        """
        年级日程管理列表视图
        :param request: HTTP请求对象
        :param grade_id: 年级ID
        :return: 渲染的模板响应
        """
        try:
            # 从请求参数获取年级ID（如果未通过URL传递）
            if not grade_id:
                grade_id = request.GET.get('grade_id')

            # 准备上下文
            context = _prepare_common_context(grade_id=grade_id)

            return render(request, 'schedule_manager/grade_schedule_list.html', context)
        except Exception as e:
            logger.error(f"年级日程管理列表视图加载失败: {str(e)}", exc_info=True)
            messages.error(request, f"页面加载失败: {str(e)}")
            return render(request, 'schedule_manager/grade_schedule_list.html', {})

    

    @staticmethod
    @login_required
    def schedule_manager_list(request, grade_id=None, class_id=None):
        """
        日程管理列表视图，支持AJAX请求
        :param request: HTTP请求对象
        :param grade_id: 年级ID (年级日程)
        :param class_id: 班级ID (班级日程)
        :return: 渲染的模板响应或JSON数据
        """
        try:
            # 确定年级ID
            if class_id and not grade_id:
                try:
                    grade_id = ClassInfo.objects.get(id=class_id).grade_id
                except ClassInfo.DoesNotExist:
                    logger.warning(f"班级ID不存在: {class_id}")
                    pass
            if not grade_id:
                # 从查询参数获取年级ID
                grade_id = request.GET.get('grade_id')

            # 准备上下文
            context = _prepare_common_context(grade_id=grade_id, class_id=class_id)

            return render(request, 'schedule_manager/list.html', context)
        except Exception as e:
            logger.error(f"日程管理列表视图加载失败: {str(e)}", exc_info=True)
            messages.error(request, f"页面加载失败: {str(e)}")
            return render(request, 'schedule_manager/list.html', {})


    @staticmethod
    @login_required
    def teacher_course_list(request, class_id):
        """
        教师课程列表视图，支持AJAX请求
        :param request: HTTP请求对象
        :param class_id: 班级ID
        :return: 渲染的模板响应或JSON数据
        """
        try:
            # 确定年级ID
            grade_id = None
            if class_id:
                try:
                    grade_id = ClassInfo.objects.get(id=class_id).grade_id
                except ClassInfo.DoesNotExist:
                    logger.warning(f"班级ID不存在: {class_id}")
                    pass
            if not grade_id:
                # 从查询参数获取年级ID
                grade_id = request.GET.get('grade_id')

            # 准备上下文
            context = _prepare_common_context(grade_id=grade_id, class_id=class_id)

            return render(request, 'schedule_manager/teacher_course_list.html', context)
        except Exception as e:
            logger.error(f"教师课程列表视图加载失败: {str(e)}", exc_info=True)
            messages.error(request, f"页面加载失败: {str(e)}")
            return render(request, 'schedule_manager/teacher_course_list.html', {})

        
    @staticmethod
    @login_required
    def class_course_list(request, class_id=None):
        """
        班级课程列表视图，支持AJAX请求
        :param request: HTTP请求对象
        :param class_id: 班级ID
        :return: 渲染的模板响应或JSON数据
        """
        try:
            # 优先使用URL参数中的class_id，如果没有则尝试从GET参数获取
            if not class_id:
                classinfo = ClassInfo.objects.filter(homeroom_teacher=request.user).first()
                if classinfo:
                    class_id = classinfo.id
                else:
                    class_id = None

            # 确定年级ID
        except Exception as e:
            logger.error(f"班级课程列表视图加载失败: {str(e)}", exc_info=True)
            messages.error(request, f"页面加载失败: {str(e)}")
            return render(request, 'schedule_manager/class_course_list.html', {})
        grade_id = None
        if class_id:
            try:
                class_obj = ClassInfo.objects.get(id=class_id)
                grade_id = class_obj.grade_id
            except ClassInfo.DoesNotExist:
                pass

        # 准备上下文
        context = _prepare_common_context(grade_id=grade_id, class_id=class_id)

        return render(request, 'schedule_manager/class_course_list.html', context)



    @staticmethod
    @login_required
    def grade_schedule_list(request, grade_id=None):
        """
        年级日程管理列表视图
        :param request: HTTP请求对象
        :param grade_id: 年级ID
        :return: 渲染的模板响应
        """
        # 从请求参数获取年级ID
        if not grade_id:
            grade_id = request.GET.get('grade_id')

        # 准备上下文
        context = _prepare_common_context(grade_id=grade_id)

        return render(request, 'schedule_manager/grade_schedule_list.html', context)
    
   